//
//  JCContacterDBManager.swift
//  JChat
//
//  Created by JIGUANG on 2017/5/4.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import FMDB
import JMessage
import MTCategory


/// 查看验证消息
enum MTRequestVerifyType: Int {
    /// 所有类型请求消息
    case all
    /// 个人添加好友消息
    case single = 1
    /// 申请加入群组验证消息
    case group = 2
}

final class JCVerificationInfoDB: NSObject {
    
    static let shareInstance = JCVerificationInfoDB()
    
    var queue: FMDatabaseQueue?
    
    private override init() {
        super.init()
        _createDB()
    }
    
    private func _createDB() {
        let user = JMSGUser.myInfo()
        if user.username.isEmpty {
            return
        }
        let dir = user.username + user.appKey!
        
        var path = "\(NSHomeDirectory())/Documents/\(dir)"
        
        if createPath(path) {
            path = path + "/VerificationInfo.db"
            debugPrint(path)
            queue = FMDatabaseQueue(path: path)
            /// 创建好友列表 - 表结构
            /*
             * verType 1 - 好友申请, 2 - 俱乐部申请
             */
            let sql = "create table IF NOT EXISTS VerificationInfo(id integer primary key autoincrement,username text not null,appkey text not null,nickname text,resaon text,state integer,timestamp TimeStamp NOT NULL DEFAULT (datetime('now','localtime')), initiator text not null, verType integer NOT NULL DEFAULT 1, eventId text, giftCount integer, province text, city text, area text, readState integer DEFAULT 0, clubId text)"
            
            queue?.inDatabase { (db) in
                db.executeUpdate(sql, withArgumentsIn: [])
            }
        }
    }
    
    func dropTable() {
        if queue == nil {
            _createDB()
            dropTable()
        }
        let sql = "drop table if exists VerificationInfo"
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func updateData(_ info: JCVerificationInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let sql = "UPDATE VerificationInfo SET nickname='\(info.nickname)', state = \(info.state), eventId = '\(info.eventId)'  WHERE username='\(info.username)' and appkey='\(info.appkey)' and state != 2"
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func insertData(_ info: JCVerificationInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let delSql = "delete from VerificationInfo where username='\(info.username)' and appkey='\(info.appkey)'"
        queue?.inDatabase { (db) in
            db.executeUpdate(delSql, withArgumentsIn: [])
        }
        var sql = ""
        if info.resaon == "" {
            sql = "insert into VerificationInfo (username, nickname, appkey, state, initiator, verType, eventId, clubId) values ('\(info.username)','\(info.nickname)','\(info.appkey)',\(String(describing: info.state)), '\(info.initiator)', '\(info.type.rawValue)', '\(info.eventId)', '\(info.clubId)')"
        } else {
            sql = "insert into VerificationInfo (username, nickname, appkey, resaon, state, initiator, verType, eventId, clubId) values ('\(info.username)','\(info.nickname)','\(info.appkey)','\(info.resaon)',\(String(describing: info.state)), '\(info.initiator)', '\(info.type.rawValue)', '\(info.eventId)', '\(info.clubId)')"
        }
        
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func delete(_ info: JCVerificationInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let delSql = "delete from VerificationInfo where id=\(String(describing: info.id))"
        queue?.inDatabase { (db) in
            db.executeUpdate(delSql, withArgumentsIn: [])
        }
    }
    
    /// 查询申请验证消息未处理条目
    /// - Parameter verType: 筛选验证条件
    /// - 1 - 好友申请, 2 - 俱乐部申请, 0 - 所有消息
    func quaryRequestCountData(verType: Int, block: ((Int) -> Void)?) {
        if queue == nil {
            _createDB()
            let user = JMSGUser.myInfo()
            if user.username.isEmpty {
                block?(0)
            }
            //let _ = quaryRequestCountData(verType: 0, block: block)
        }
        
        let sql = "select * from VerificationInfo WHERE verType='\(verType)' and readState=0 ORDER BY id DESC"
        queue?.inDatabase { (db) in
            let resultSet = db.executeQuery(sql, withArgumentsIn: [])
            var count = 0
            while (resultSet?.next())! {
                count = count + 1
            }
            block?(count)
            resultSet?.close()
        }
    }
    
    
    /// 设置所有请求消息为已读 - 清除小红点
    /// - Parameter verType: 筛选验证条件
    /// - 1 - 好友申请, 2 - 俱乐部申请, 0 - 所有消息
    func updateAllUnReadRequestMessage(verType: Int) {
        if queue == nil {
            _createDB()
            let user = JMSGUser.myInfo()
            if user.username.isEmpty {
                return
            }
        }
        
        let sql = "UPDATE VerificationInfo SET readState = 1 WHERE verType = \(verType)"
        queue?.inDatabase { (db) in
            let resultSet = db.executeUpdate(sql, withArgumentsIn: [])
            //resultSet.close()
        }
    }
    
    /// 查询申请验证消息类型
    /// - Parameter verType: 筛选验证条件
    /// - 1 - 好友申请, 2 - 俱乐部申请, 0 - 所有消息
    func quaryData(verType: Int) -> [JCVerificationInfo] {
        if queue == nil {
            _createDB()
            let user = JMSGUser.myInfo()
            if user.username.isEmpty {
                return []
            }
            let _ = quaryData(verType: 0)
        }
        var infos: [JCVerificationInfo] = []
        var sql = ""
        if verType == 0 {
            sql = "select * from VerificationInfo ORDER BY id DESC"
        } else {
            sql = "select * from VerificationInfo  WHERE verType=\(verType) ORDER BY id DESC"
        }
        queue?.inDatabase { (db) in
            let resultSet = db.executeQuery(sql, withArgumentsIn: [])
            while (resultSet?.next())! {
                let info = JCVerificationInfo()
                info.id = Int((resultSet?.int(forColumn: "id"))!)
                info.username = (resultSet?.string(forColumn: "username"))!
                info.initiator = (resultSet?.string(forColumn: "initiator"))!
                info.nickname = (resultSet?.string(forColumn: "nickname"))!
                info.appkey = (resultSet?.string(forColumn: "appkey"))!
                info.resaon = (resultSet?.string(forColumn: "resaon")) ?? ""
                info.state = Int((resultSet?.int(forColumn: "state"))!)
                info.timestamp = DateManager.timestamp(timeString: (resultSet?.string(forColumn: "timestamp")!)!, format: "yyyy-MM-dd HH:mm:ss")
                info.type = Int((resultSet?.int(forColumn: "verType"))!) == 0 ? MTRequestVerifyType.all  : Int((resultSet?.int(forColumn: "verType"))!) == 1 ? MTRequestVerifyType.single : MTRequestVerifyType.group
                info.eventId = (resultSet?.string(forColumn: "eventId")) ?? ""
                info.giftCount = Int((resultSet?.int(forColumn: "giftCount"))!)
                info.city = (resultSet?.string(forColumn: "city")) ?? ""
                info.province = (resultSet?.string(forColumn: "province")) ?? ""
                info.area = (resultSet?.string(forColumn: "area")) ?? ""
                info.clubId = (resultSet?.string(forColumn: "clubId")) ?? ""
                infos.append(info)
            }
            resultSet?.close()
        }
        return infos
    }
    
    // MARK: - private func
    private func createPath(_ path: String) -> Bool {
        var isDir: ObjCBool = ObjCBool(false)
        
        if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue {
            return true
        } else {
            try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            return true
        }
    }
}
